package com.example.topic;

import com.example.utils.RabbitUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author hanj.cn@outlook.com
 * @date 2022/1/8 10:47
 */
public class Consumer02 {

    /**
     * 交换机名字
     */
    private static final String EXCHANGE_NAME = "topic_logs";

    /**
     * 接收消息
     *
     * @param args 参数
     */
    public static void main(String[] args) throws IOException {
        // 得到信道
        Channel channel = RabbitUtil.getChannel();
        // 用信道声明交换机
        assert channel != null;
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");
        // 声明队列
        String queueName = "Q2";
        channel.queueDeclare(queueName, false, false, false, null);
        // 在信道中进行队列的捆绑
        channel.queueBind(queueName, EXCHANGE_NAME, "*.*.rabbit");
        channel.queueBind(queueName, EXCHANGE_NAME, "lazy.#");
        System.out.println("等待接收消息中...");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println("从队列" + queueName + "接收键为" + delivery.getEnvelope().getRoutingKey() + "的消息:" + message);
        };
        // 接收消息
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {
        });
    }

}
